package com.kingtown.inventory.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.hutool.core.util.StrUtil;
import com.google.gson.reflect.TypeToken;
import com.kingtown.inventory.MainApplication;
import com.kingtown.inventory.R;
import com.kingtown.inventory.Utils;
import com.kingtown.inventory.domain.bo.AssetOutBo;
import com.kingtown.inventory.domain.bo.SubmitBo;
import com.kingtown.inventory.domain.dto.AssetDto;
import com.kingtown.inventory.domain.dto.KiClient;
import com.kingtown.inventory.domain.dto.KiFloor;
import com.kingtown.inventory.domain.dto.KiPosition;
import com.kingtown.inventory.domain.so.AssetSo;
import com.kingtown.inventory.net.NetWorkManager;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import java.util.*;
import java.util.stream.Collectors;

public class OutActivity extends AppCompatActivity implements View.OnClickListener {
    MainApplication mApplication;
    RecyclerView recyclerView;
    Context _this;

    Button btnReset, btnStart, btnSubmit;

    TextView txtClientName, txtFloor, txtPosition, txtSelectClient, txtSelectFloor, txtSelectPosition,
            statTotal;
    List<KiClient> clients = new ArrayList<>();
    List<KiFloor> floors = new ArrayList<>();
    List<KiPosition> positions = new ArrayList<>();

    Map<String, KiClient> clientMap = new HashMap<>();
    Map<String, KiFloor> floorMap = new HashMap<>();
    Map<String, KiPosition> positionMap = new HashMap<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_out);
        _this = this;
        mApplication = (MainApplication) this.getApplication();
        recyclerView = (RecyclerView) findViewById(R.id.out_list);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(mApplication.assetAdapter);

        btnReset = findViewById(R.id.btn_reset);
        btnStart = findViewById(R.id.btn_start);
        btnSubmit = findViewById(R.id.btn_submit);
        btnReset.setOnClickListener(this);
        btnStart.setOnClickListener(this);
        btnSubmit.setOnClickListener(this);

        txtClientName = findViewById(R.id.txt_client_name);
        txtFloor = findViewById(R.id.txt_floor);
        txtPosition = findViewById(R.id.txt_position);
        txtSelectClient = findViewById(R.id.txt_select_client);
        txtSelectFloor = findViewById(R.id.txt_select_floor);
        txtSelectPosition = findViewById(R.id.txt_select_position);
        txtSelectClient.setOnClickListener(this);
        txtSelectFloor.setOnClickListener(this);
        txtSelectPosition.setOnClickListener(this);

        statTotal = findViewById(R.id.stat_total);

    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_reset -> {
//                Toast.makeText(_this, "reset", Toast.LENGTH_SHORT).show();
                mApplication.resetData();
                updateStatic();
            }
            case R.id.btn_start -> {
//                Toast.makeText(_this, "start", Toast.LENGTH_SHORT).show();
                if (mApplication.rawMap.isEmpty()) {
                    Toast.makeText(_this, "请先选择出库对象", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (btnStart.getText().equals("开始扫描")) {
                    if (mApplication.startInventory()) {
                        btnStart.setText("停止扫描");
                        startTimer();
                    } else {
                        Toast.makeText(_this, "开始扫描失败，请退出其他软件", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    if (mApplication.stopInventory()) {
                        btnStart.setText("开始扫描");
                        stopTimer();
                    } else {
                        Toast.makeText(_this, "停止扫描失败，请退出其他软件", Toast.LENGTH_SHORT).show();
                    }
                }
            }
            case R.id.btn_submit -> {
                if (btnStart.getText().equals("停止扫描")) {
                    if (mApplication.stopInventory()) {
                        btnStart.setText("开始扫描");


                    } else {
                        Toast.makeText(_this, "停止扫描失败，请退出其他软件", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                final EditText et = new EditText(this);
                new AlertDialog.Builder(this).setTitle("请输入出库原因")
                        .setView(et)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //按下确定键后的事件
                                handleSubmit(et.getText().toString());
                            }
                        }).setNegativeButton("取消", null).show();
            }
            case R.id.txt_select_client -> loadClient();
            case R.id.txt_select_floor -> loadFloor();
            case R.id.txt_select_position -> loadPosition();
            default -> {
            }
        }
    }

    @SuppressLint({"CheckResult", "NotifyDataSetChanged"})
    private void loadData() {
        mApplication.rawList.clear();
        mApplication.rawMap.clear();
        mApplication.assetList.clear();
        AssetSo so = new AssetSo();
        if (mApplication.selectClient != null) {
            so.setClientId(mApplication.selectClient.getId());
        }
        if (mApplication.selectFloor != null) {
            so.setFloor(mApplication.selectFloor.getFloor());
        }
        if (mApplication.selectPosition != null) {
            so.setPosition(mApplication.selectPosition.getPosition());
        }
        NetWorkManager.request()
                .assetAll(so)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(res -> {
                    if (res.isSuccess()) {
                        Log.i("res", res.toString());
                        String assetStr = mApplication.gson.toJson(res.getData());
                        List<AssetDto> assetList = mApplication.gson.fromJson(assetStr, new TypeToken<List<AssetDto>>() {
                        }.getType());
                        assetList.forEach(assetDto -> {
                            assetDto.setInventoryStatus(0);
                        });
//                        mApplication.rawList.addAll(assetList);

                        if (StrUtil.isNotBlank(so.getPosition())) {
                            mApplication.rawList.addAll(assetList.stream().filter(s ->
                                    so.getPosition().equals(s.getAssetPosition()) &&
                                            so.getFloor().equals(s.getAssetFloor())).collect(Collectors.toList()));
                        } else if (StrUtil.isNotBlank(so.getFloor())) {
                            mApplication.rawList.addAll(assetList.stream().filter(s ->
                                    so.getFloor().equals(s.getAssetFloor())).collect(Collectors.toList()));
                        } else {
                            mApplication.rawList.addAll(assetList);
                        }
                        mApplication.rawMap.putAll(mApplication.rawList.stream().collect(Collectors.toMap(AssetDto::getAssetEpc, s -> s)));
                        statTotal.setText("0");
                        updateStatic();
                        mApplication.assetAdapter.notifyDataSetChanged();
                    } else {
                        Toast.makeText(_this, "请求失败", Toast.LENGTH_SHORT).show();
                    }
                }, throwable -> {
                    Toast.makeText(_this, "请求失败：" + throwable + "！", Toast.LENGTH_SHORT).show();
                    Utils.hideProgressDialog();
                });
    }


    @SuppressLint("CheckResult")
    private void loadClient() {
        txtSelectClient.setText("选择客户");
        NetWorkManager.request()
                .listClient()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(res -> {
                    if (res.isSuccess()) {
                        Log.i("res", res.toString());
                        String jsonString = mApplication.gson.toJson(res.getData());
                        List<KiClient> clients = mApplication.gson.fromJson(jsonString, new TypeToken<List<KiClient>>() {
                        }.getType());
                        clientMap = clients.stream().collect(Collectors.toMap(KiClient::getClientName, s -> s));
                        List<String> clientNames = clients.stream().map(KiClient::getClientName).collect(Collectors.toList());
                        String[] clientArr = clientNames.toArray(new String[clientNames.size()]);
                        android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(this)
                                .setTitle("请选择客户")//默认为0表示选中第一个项目
                                .setSingleChoiceItems(clientArr, 0, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mApplication.selectClient = clientMap.get(clientArr[which]);
                                    }
                                })
                                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        txtSelectClient.setText("重选");
                                        if (mApplication.selectClient == null) {
                                            mApplication.selectClient = clients.get(0);
                                        }
                                        txtClientName.setText(mApplication.selectClient.getClientName());
                                        mApplication.selectFloor = null;
                                        mApplication.selectPosition = null;
                                        txtFloor.setText("");
                                        txtPosition.setText("");
                                        txtSelectFloor.setText("选择楼层");
                                        txtSelectPosition.setText("选择房间");
                                        mApplication.cacheEpcList.clear();
                                        loadData();
                                    }
                                })
                                .setNegativeButton("取消", null)
                                .create();
                        alertDialog.show();
                    } else {
                        Toast.makeText(_this, "请求失败", Toast.LENGTH_SHORT).show();
                    }
                }, throwable -> {
                    Toast.makeText(_this, "请求失败：" + throwable + "！", Toast.LENGTH_SHORT).show();
                    Utils.hideProgressDialog();
                });
    }

    @SuppressLint("CheckResult")
    private void loadFloor() {
        if (mApplication.selectClient == null) {
            Toast.makeText(_this, "请先选择客户", Toast.LENGTH_SHORT).show();
            return;
        }
        txtSelectFloor.setText("选择楼层");
        NetWorkManager.request()
                .listFloor(mApplication.selectClient.getId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(res -> {
                    if (res.isSuccess()) {
                        Log.i("res", res.toString());
                        String jsonString = mApplication.gson.toJson(res.getData());
                        List<KiFloor> floors = mApplication.gson.fromJson(jsonString, new TypeToken<List<KiFloor>>() {
                        }.getType());
                        floorMap = floors.stream().collect(Collectors.toMap(KiFloor::getFloor, s -> s));
                        List<String> floorNames = floors.stream().map(KiFloor::getFloor).collect(Collectors.toList());
                        String[] floorArr = floorNames.toArray(new String[floorNames.size()]);
                        android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(this)
                                .setTitle("请选择楼层")//默认为0表示选中第一个项目
                                .setSingleChoiceItems(floorArr, 0, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mApplication.selectFloor = floorMap.get(floorArr[which]);

                                    }
                                })
                                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                        txtSelectFloor.setText("重选");
                                        if (mApplication.selectFloor == null) {
                                            mApplication.selectFloor = floors.get(0);
                                        }
                                        txtFloor.setText(mApplication.selectFloor.getFloor());
                                        mApplication.selectPosition = null;
                                        txtPosition.setText("");
                                        txtSelectPosition.setText("选择房间");
                                        mApplication.cacheEpcList.clear();
                                        loadData();
                                    }
                                })
                                .setNegativeButton("取消", null)
                                .create();
                        alertDialog.show();
                    } else {
                        Toast.makeText(_this, "请求失败", Toast.LENGTH_SHORT).show();
                    }
                }, throwable -> {
                    Toast.makeText(_this, "请求失败：" + throwable + "！", Toast.LENGTH_SHORT).show();
                    Utils.hideProgressDialog();
                });
    }

    @SuppressLint("CheckResult")
    private void loadPosition() {
        if (mApplication.selectFloor == null) {
            Toast.makeText(_this, "请先选择楼层", Toast.LENGTH_SHORT).show();
            return;
        }
        txtSelectPosition.setText("选择房间");
        NetWorkManager.request()
                .listPosition(mApplication.selectFloor.getId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(res -> {
                    if (res.isSuccess()) {
                        Log.i("res", res.toString());
                        String jsonString = mApplication.gson.toJson(res.getData());
                        List<KiPosition> positions = mApplication.gson.fromJson(jsonString, new TypeToken<List<KiPosition>>() {
                        }.getType());
                        positionMap = positions.stream().collect(Collectors.toMap(KiPosition::getPosition, s -> s));
                        List<String> positionNames = positions.stream().map(KiPosition::getPosition).collect(Collectors.toList());
                        String[] positionArr = positionNames.toArray(new String[positionNames.size()]);
                        android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(this)
                                .setTitle("请选择房间")//默认为0表示选中第一个项目
                                .setSingleChoiceItems(positionArr, 0, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mApplication.selectPosition = positionMap.get(positionArr[which]);
                                    }
                                })
                                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        txtSelectPosition.setText("重选");
                                        if (mApplication.selectPosition == null)
                                            mApplication.selectPosition = positions.get(0);
                                        txtPosition.setText(mApplication.selectPosition.getPosition());
                                        mApplication.cacheEpcList.clear();
                                        loadData();
                                    }
                                })
                                .setNegativeButton("取消", null)
                                .create();
                        alertDialog.show();
                    } else {
                        Toast.makeText(_this, "请求失败", Toast.LENGTH_SHORT).show();
                    }
                }, throwable -> {
                    Toast.makeText(_this, "请求失败：" + throwable + "！", Toast.LENGTH_SHORT).show();
                    Utils.hideProgressDialog();
                });
    }

    Timer updateStaticTimer;
    TimerTask updateStaticTask;

    public void startTimer() {
        this.stopTimer();
        updateStaticTimer = new Timer();
        updateStaticTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(() -> updateStatic());
            }
        };
        this.updateStaticTimer.schedule(this.updateStaticTask, 0, 200);
    }

    public void stopTimer() {
        if (this.updateStaticTimer != null) {
            this.updateStaticTimer.cancel();
        }
    }

    private void updateStatic() {
        statTotal.setText(mApplication.assetList.size() + "");
//        statEd.setText(mApplication.assetList.stream().filter(s -> s.getInventoryStatus().equals(1)).count() + "");
//        statUn.setText(mApplication.assetList.stream().filter(s -> s.getInventoryStatus().equals(0)).count() + "");
//        statDuo.setText(mApplication.assetList.stream().filter(s -> s.getInventoryStatus().equals(2)).count() + "");
    }

    @SuppressLint("CheckResult")
    private void handleSubmit(String reason) {
//        Utils.showProgressDialog(_this,"提示","数据提交中...");
//        SubmitBo bo = new SubmitBo();
//        bo.setList(mApplication.assetList);
        AssetOutBo bo = new AssetOutBo();
        bo.setReason(reason);
        bo.setAssets(mApplication.assetList);
        NetWorkManager.request()
                .submitOutbound(bo)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(res -> {
                    if (res.isSuccess()) {


                        mApplication.rawList.clear();
                        mApplication.rawMap.clear();
                        mApplication.assetList.clear();
                        mApplication.selectClient = null;
                        mApplication.selectFloor = null;
                        mApplication.selectPosition = null;

                        mApplication.resetData();
                        updateStatic();
                        txtClientName.setText("");
                        txtFloor.setText("");
                        txtPosition.setText("");
                        txtSelectClient.setText("选择客户");
                        txtSelectFloor.setText("选择楼层");
                        txtSelectPosition.setText("选择房间");
                        statTotal.setText("0");
                        Toast.makeText(_this, "提交成功", Toast.LENGTH_SHORT).show();
                        Utils.hideProgressDialog();
                    } else {
                        Toast.makeText(_this, "提交失败", Toast.LENGTH_SHORT).show();
                        Utils.hideProgressDialog();
                    }
                }, throwable -> {
                    Toast.makeText(_this, "提交失败：" + throwable + "！", Toast.LENGTH_SHORT).show();
                    Utils.hideProgressDialog();
                });


    }

    Menu mMenu;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_setting, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_set_power:
                Utils.showSingleChoiceDialog(this, mApplication.mReader, mApplication.loopFlag);
                break;

        }
        return super.onOptionsItemSelected(item);
    }
}